package Device.scanner_mp86;

import java.text.SimpleDateFormat;

import everbright.uart.library.SerialPortConfig;
import everbright.uart.library.SerialPortHelper;

public class mp86_control {


    private SerialPortHelper scanner_mp86_uart;

    private static final String TAG = "PrinterSerialPort";

    public boolean isOpen;


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // 国际化标志时间格式类
    /*******************************************************************************
     * Function Name  : openSerialPort
     * Description    : 打开相应串口
     * Input          : None
     * Return         : <0时失败，>=0时成功
     *******************************************************************************/
    public int openSerialPort(){

        // 串口参数
        SerialPortConfig serialPortConfig = new SerialPortConfig();
        serialPortConfig.mode = 0;
        serialPortConfig.path = "/dev/ttyS1";
        serialPortConfig.baudRate = 115200;
        serialPortConfig.dataBits = 8;
        serialPortConfig.parity   = 'N';
        serialPortConfig.stopBits = 1;

        if(isOpen) return 0;
        // 初始化串口
        scanner_mp86_uart = new SerialPortHelper(32);
        // 设置串口参数
        scanner_mp86_uart.setConfigInfo(serialPortConfig);
        // 开启串口
        isOpen = scanner_mp86_uart.openDevice();
        if(!isOpen){
            return -1;
        }
        return 1;   //正常返回正值
    }
    /*******************************************************************************
     * Function Name  : closeSerialPort
     * Description    : 关闭相应串口
     * Input          : None
     * Return         : None
     *******************************************************************************/
    public void closeSerialPort() {
        if(isOpen){
            scanner_mp86_uart.closeDevice();
            isOpen  =   false;
        }
    }

    /*******************************************************************************
     * Function Name  : Check_Response_is_OK
     * Description    : 检查串口命令校验和
     * Input          : None
     * Return         : true:成功；
     * 影 响			 ：None
     *******************************************************************************/
    private boolean Check_Response_is_OK(byte[] received_buffer )
    {
        byte check;
        int i,len,len1;

        if((received_buffer[0]==(byte)0x55)&&(received_buffer[1]==(byte)0xAA))	  //检查命令头
        {
            len1 = received_buffer[5];    //包长度
            len1 = (len1 << 8) | received_buffer[4];
            check	=	0;
            len = len1 +6;
            for(i=0;i<len;i++)
            {
                    check	^=	received_buffer[i];
            }
            if(check==received_buffer[len])
                return true;
            else
                return false;
        }
        return false;

    }
    /*****************************************************************
     程序名: Scanner_Transceive_Command
     输入: send_len:为data数据长度，命令字不包含在内
     输出: 无
     返回: 无
     说明：JCM接口，发送接收指令
     *****************************************************************/
    private int Scanner_Transceive_Command(byte cmd,byte[] data,int send_len,byte[]receive_buf)
    {
        int i,len,size;
        int ret;
        byte[] RS232_Cmd_BUFFER   =   new byte[6+send_len];

        len = send_len+7;			//传入send_len，为data数据长度，命令字不包含在内
        RS232_Cmd_BUFFER[0] = (byte)0x55;
        RS232_Cmd_BUFFER[1] = (byte)0xAA;
        RS232_Cmd_BUFFER[2] = cmd;
        RS232_Cmd_BUFFER[3] = (byte)(send_len);
        RS232_Cmd_BUFFER[4] = (byte)(send_len>>8);
        //数据域
        if(send_len>0)
        {
            for(i=0;i<send_len;i++)
            {
                RS232_Cmd_BUFFER[5+i] = data[i];
            }
        }
        //计算校验字,从命令头到数据域最后一字节的逐字节异或
        byte check = 0;
        len = send_len+5;
        for(i=0;i<len;i++)
        {
            check ^= RS232_Cmd_BUFFER[i];
        }
        RS232_Cmd_BUFFER[len]   = check;
        scanner_mp86_uart.sendCommands(RS232_Cmd_BUFFER,0);
        //len = Wait_Receive(100);
        //if(len>=UART_CMD_HEADER_TAIL_LENGTH)
        byte[] all_receive_buf =  scanner_mp86_uart.receiveCommands(80,200);
        if (all_receive_buf != null)
        {
            if(Check_Response_is_OK(all_receive_buf))
            {
                //判断标识字是否为0， 0x00 则代表成功应答，其它失败或错误
                if(all_receive_buf[3]!=0)
                {
                        return all_receive_buf[3];
                }

                len = all_receive_buf[5];	//包长度
                len = (len<<8)|all_receive_buf[4];	//包长度
                receive_buf[0] = all_receive_buf[4];
                receive_buf[1] = all_receive_buf[5];
                if(len>0) {
                    for (i = 0; i < len; i++) {
                        receive_buf[2+i] = all_receive_buf[i + 6];
                    }
                }
                return mp86_Constant.SCANNER_RESPONSE_OK;
            }
            else
            {
                return mp86_Constant.SCANNER_RESPONSE_VERIFY_ERROR;
            }
        }
        else
        {
            ret	=	mp86_Constant.SCANNER_RESPONSE_TIMEOUT;;
        }
        return ret;
    }


    //设置各种条码启用禁用
    public int Set_QR_DM_Barcode_NFC_Function(boolean QR_enable,boolean DM_enable,boolean bar_enable,boolean NFC_enable)
    {
        int result;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer   =   new byte[16];
        send_buffer[0] = 0;
        send_buffer[1] = 1;
        if(QR_enable)
        {
            send_buffer[0] |= 0x01;
        }
        if(DM_enable)
        {
            send_buffer[0] |= 0x02;
        }
        if(bar_enable)
        {
            send_buffer[0] |= 0x04;
        }
        if(NFC_enable)
        {
            send_buffer[0] |= 0x08;
        }
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_QR_DM_BARCODE_NFC_SETTING,send_buffer,1,response_buffer);
        return result;
    }
    //设置各种条码启用禁用
    public int Set_Scan_Work_Mode(byte mode,int interval_second)
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer   =   new byte[16];
        send_buffer[0] = mode;
        if(mode==mp86_Constant.SCAN_WORK_MODE_INTERVAL)
        {
            sent_len = 3;
            send_buffer[1] = (byte)(interval_second&0xff);
            send_buffer[2] = (byte)((interval_second>>8)&0xff);
        }
        else
        {
            sent_len = 1;
        }
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_SCAN_WORK_MODE,send_buffer,sent_len,response_buffer);
        return result;
    }
    //设置扫码成功后,LED行为
    public int Set_Scan_Success_LED_Status(byte led_status)
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer   =   new byte[16];
        send_buffer[0] = led_status;
        sent_len = 1;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_SCAN_SUCCESS_LED_STATUS,send_buffer,sent_len,response_buffer);
        return result;
    }
    //设置扫码成功后,蜂鸣器行为
    public int Set_Scan_Success_Beep_Status(byte beep_status)
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer   =   new byte[16];
        send_buffer[0] = beep_status;
        sent_len = 1;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_SCAN_SUCCESS_BEEP_STATUS,send_buffer,sent_len,response_buffer);
        return result;
    }
    //检查设备状态查询
    public int Check_Device_Is_OK()
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer =   new byte[16];;
        sent_len = 0;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_CHECK_DEVICE_STATUS,send_buffer,sent_len,response_buffer);
        return result;
    }
    //LED灯和蜂鸣器控制
    public int Set_LED_And_Beep_Control(byte led_or_Beep,int count,int on_time,int interval_time)
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer   =   new byte[16];
        byte bTemp;
        send_buffer[0] = led_or_Beep;
        send_buffer[1] = (byte)count;
        bTemp = (byte)(on_time/50);
        send_buffer[2] = bTemp;
        bTemp = (byte)(interval_time/50);
        send_buffer[3] = bTemp;
        sent_len = 4;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_LED_AND_BEEP_CONTROL,send_buffer,sent_len,response_buffer);
        return result;
    }
    //扫码打开或关闭
    public int Scanner_OnOff(byte on_off)
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer   =   new byte[16];
        send_buffer[0] = on_off;
        sent_len = 1;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_SCANNER_ON_OFF,send_buffer,sent_len,response_buffer);
        return result;
    }
    //扫描器设置扫描结果
    public int Scanner_Result_Notify_Mode(byte mode)
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer = new byte[16];
        send_buffer[0] = mode;
        sent_len = 1;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_SCANNER_RESULT_NOTIFY_MODE,send_buffer,sent_len,response_buffer);
        return result;
    }
    //扫描器打开或关闭命令模式
    public int Open_Command_Mode(boolean _open)
    {
        int result,sent_len;
        byte[] send_buffer   =   new byte[8];
        byte[] response_buffer = new byte[16];
        if(_open)
        {//进入命令模式
            send_buffer[0] = 1;
        }
        else
        {//退出命令模式
            send_buffer[0] = 0;
        }
        sent_len = 1;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_CONTROL_COMMAND_MODE,send_buffer,sent_len,response_buffer);
        return result;
    }


    /**
     * bytes转换成十六进制字符串
     * @param b byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b,int len)
    {
        String stmp="";
        StringBuilder sb = new StringBuilder("");
        for (int n=0;n<len;n++)
        {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length()==1)? "0"+stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    //扫描器获取扫描结果
    public int Scanner_Get_Result(byte[] scanInfo)
    {
        int result,i,sent_len,response_len;
        byte[] send_buffer   =   new byte[16];
        byte[] responseInfo  =   new byte[300];
        sent_len =0;
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_SCANNER_Get_Result,send_buffer,sent_len,responseInfo);
        if(result==mp86_Constant.SCANNER_RESPONSE_OK)
        {
            response_len = responseInfo[1];
            response_len = (response_len<<8)|responseInfo[0];
            if(response_len>0)
            {
                if((responseInfo[2]==(byte)'Q')&&(responseInfo[3]==(byte)'R')&&(responseInfo[4]==(byte)':'))
                {
                    for (i = 0; i < response_len-3; i++) {
                        scanInfo[i] = responseInfo[5 + i];
                    }
                    return mp86_Constant.SCANNER_RESPONSE_RESULT_QR;
                }
                else if((responseInfo[2]==(byte)'C')&&(responseInfo[3]==(byte)'I')&&(responseInfo[4]==(byte)'D'))
                {
                    for (i = 0; i < response_len-4; i++) {
                        scanInfo[i] = responseInfo[6 + i];
                    }
                    return mp86_Constant.SCANNER_RESPONSE_RESULT_CARD;
                }
                else
                {
                    for (i = 0; i < response_len; i++) {
                        scanInfo[i] = responseInfo[2 + i];
                    }
                    return mp86_Constant.SCANNER_RESPONSE_RESULT_QR;
                }
            }
            else
            {
                return mp86_Constant.SCANNER_RESPONSE_RESULT_NONE;
            }
        }
        else {
            return result;
        }
    }
    //扫描器读RF卡
    public int Read_S50_RF_Card_Block(byte keyType,byte block,byte[] key,byte[] blockInfo)
    {
        int result,sent_len,i,response_len;
        byte[] send_buffer   =   new byte[16];
        byte[] responseInfo  =   new byte[300];
        sent_len = 8;

        send_buffer[0] = keyType;   //0x60 表示采用 A 密钥认证；  0x61 表示采用 B 密钥认证
        send_buffer[1] = block;
        send_buffer[2]  =   key[0];
        send_buffer[3]  =   key[1];
        send_buffer[4]  =   key[2];
        send_buffer[5]  =   key[3];
        send_buffer[6]  =   key[4];
        send_buffer[7]  =   key[5];
        result = Scanner_Transceive_Command(mp86_Constant.REQUEST_CMD_READ_S50_CARD_BLOCK,send_buffer,sent_len,responseInfo);
        if(result==mp86_Constant.SCANNER_RESPONSE_OK)
        {
            response_len = responseInfo[1];
            response_len = (response_len<<8)|responseInfo[0];
            if(response_len>0)
            {
                for(i=0;i<response_len;i++)
                {
                    blockInfo[i] = responseInfo[2+i];
                }
                return mp86_Constant.SCANNER_RESPONSE_OK;
            }
            else
            {
                return mp86_Constant.SCANNER_RESPONSE_RESULT_NONE;
            }
        }
        else {
            return result;
        }
    }

}



